console.log("测试开发！");
// console.log(this.document);
var targetDiv = this.document.querySelector(".container");
// 若未找到容器，输出错误信息并终止执行
if (!targetDiv) {
  console.error('未找到 ".container" 元素');
}
console.log(targetDiv);

// ! 向页面插入自定义功能按钮  开始--------------------------------------------------------------------------
var feed_roll_btn; // 回溯按钮要插入的位置
var previous_page_Button; //回溯按钮上一页按钮
var next_page_Button; //回溯按钮下一页按钮
var roll_btn = this.document.querySelector(".primary-btn.roll-btn"); // B站按钮刷一刷;
var page_index = -10;

function insertDocument() {
  feed_roll_btn = this.document.querySelector(".feed-roll-btn"); // 要插入的位置

  // 创建新按钮
  previous_page_Button = document.createElement("button");
  previous_page_Button.className = "previous_page"; //#上一页
  previous_page_Button.id = "previous_page";
  previous_page_Button.style.cssText = `
      height: 38px;
      width: 38px;
      font-size: 10px;
      padding: 7px;
      background: #fff;
      color: #000;
      border: 1px solid #e3e5e7;
      border-radius: 4px;
      cursor: pointer;
      margin: 10px 10px 10px 0;
      pointer-events: auto;
      position: relative;
      z-index: 9999;
    `;
  previous_page_Button.innerHTML = `
  <svg t="1746246788184" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3473" id="mx_n_1746246788185" width="16" height="16"><path d="M309.666909 142.941091a42.589091 42.589091 0 0 1-4.654545 60.043636l-61.905455 53.061818h375.435636c169.704727 0 313.204364 138.007273 319.767273 307.665455 7.028364 179.246545-140.474182 332.194909-319.767273 332.194909h-362.58909a42.589091 42.589091 0 1 1 0-85.178182h362.58909c131.025455 0 239.802182-112.872727 234.682182-243.712-4.840727-123.950545-110.731636-225.745455-234.682182-225.745454h-387.723636l76.613818 76.613818a42.589091 42.589091 0 1 1-60.229818 60.229818L97.885091 328.797091a42.589091 42.589091 0 0 1 2.420364-62.464l149.317818-128a42.589091 42.589091 0 0 1 60.043636 4.654545z" p-id="3474"></path></svg>
  `;
  feed_roll_btn.appendChild(previous_page_Button);

  // 创建新按钮
  next_page_Button = document.createElement("button");
  next_page_Button.className = "next_page"; //下一页
  next_page_Button.id = "next_page";
  next_page_Button.style.cssText = `
      height: 38px;
      width: 38px;
      font-size: 10px;
      padding: 7px;
      background: #fff;
      color: #000;
      border: 1px solid #e3e5e7;
      border-radius: 4px;
      cursor: pointer;
      margin: 10px 10px 10px 0;
      pointer-events: auto;
      position: relative;
      z-index: 9999;
    `;
  next_page_Button.innerHTML = `
<svg t="1746246788184" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3473" width="16" height="16" style="transform: scaleY(-1);">
  <path d="M309.666909 142.941091a42.589091 42.589091 0 0 1-4.654545 60.043636l-61.905455 53.061818h375.435636c169.704727 0 313.204364 138.007273 319.767273 307.665455 7.028364 179.246545-140.474182 332.194909-319.767273 332.194909h-362.58909a42.589091 42.589091 0 1 1 0-85.178182h362.58909c131.025455 0 239.802182-112.872727 234.682182-243.712-4.840727-123.950545-110.731636-225.745455-234.682182-225.745454h-387.723636l76.613818 76.613818a42.589091 42.589091 0 1 1-60.229818 60.229818L97.885091 328.797091a42.589091 42.589091 0 0 1 2.420364-62.464l149.317818-128a42.589091 42.589091 0 0 1 60.043636 4.654545z" p-id="3474"></path>
</svg>  `;
  feed_roll_btn.appendChild(next_page_Button);
}
// ! 向页面插入自定义功能按钮  结束--------------------------------------------------------------------------

// ! 点击元素处理  开始---------------------------------------------------------------------------------------
function clickDocument() {
  // todo 上一页按钮点击逻辑
  previous_page_Button.addEventListener("click", (e) => {
    e.stopImmediatePropagation(); // 防止其他处理程序干扰
    console.log("上按钮被点击");
    let index = getCurrentIndex();
    if (page_index === -10) {
      page_index = index;
    }
    page_index -= 1;
    if (page_index >= 0) {
      const VideoData = getStoredVideoData()[page_index];
      if (VideoData[0] == null) {
        console.log("点击无效");
        page_index += 1;
        return;
      }
      // 清除渲染huisu的卡片同时清除renderedVideoIds的标记
      removeAllHuizuCards();
      renderVideoCards(VideoData, targetDiv);
      console.log("渲染结束", page_index);
    } else {
      page_index = 0;
    }
  });

  // todo 下一页按钮点击逻辑
  next_page_Button.addEventListener("click", (e) => {
    e.stopImmediatePropagation(); // 防止其他处理程序干扰
    console.log("下按钮被点击");
    let index = getCurrentIndex();
    if (page_index === -10) {
      page_index = index;
    }
    page_index += 1;
    if (page_index <= 29) {
      const VideoData = getStoredVideoData()[page_index];
      if (VideoData[0] == null) {
        console.log("点击无效");
        page_index -= 1;
        return;
      }
      removeAllHuizuCards();
      renderVideoCards(VideoData, targetDiv);
      console.log("渲染结束", page_index);
    } else {
      page_index = index;
    }
  });

  // todo B站刷一刷按钮的点击逻辑
  roll_btn.addEventListener("click", (e) => {
    e.stopImmediatePropagation(); // 防止其他处理程序干扰
    console.log("刷一刷被点击");
    try {
      removeAllHuizuCards();

      const videoData = getStoredVideoData();

      // 检查 videoData 是否是一个非空数组，且所有元素都不为空
      if (
        Array.isArray(videoData) &&
        videoData.length > 0 &&
        videoData.every((item) => item != null)
      ) {
        page_index += 1;
        storeVideoData(page_index, [], 0); // 如果所有元素都不为空，则清空 index+1 的子列表
      }
    } catch (error) {
      console.error("刷一刷操作失败:", error);
    }
  });
}

// ! 点击元素处理  结束---------------------------------------------------------------------------------------

// ! 主逻辑 开始-----------------------------------------------------------------------------------------------
insertDocument(); //向页面插入自定义功能按钮
clickDocument(); //点击元素处理
// ! 主逻辑 结束-----------------------------------------------------------------------------------------------

// ! 函数 开始--------------------------------------------------------------------------------------------------
// todo 提取卡片元素信息
function extractInformation(Cached_data) {
  let currentBatch = []; //临时数组, 将数据保存到浏览器localStorage
  Cached_data.forEach((e) => {
    if (e.classList?.contains("feed-card")) {
      // 注意：移除了类名前的点（.）
      e.style.marginTop = "22px";
    }

    // 创建数据存储对象
    let data_s = {
      video_id: "", // 视频BV号（需从href中提取）
      title: "", // 视频标题
      cover_url: "", // 视频封面URL
      play_count: "", // 播放量
      danmaku_count: "", // 弹幕数
      duration: "", // 视频时长
      up_name: "", // UP主名称
      up_url: "", // UP主空间链接
      publish_date: "", // 发布日期
      like_count: "", // 点赞数
    };

    // console.log(e);
    // 提取标题文本（trim()去除首尾空格）
    data_s.title = e
      .querySelector(".bili-video-card__info--tit a")
      .textContent.trim();

    // 提取视频链接并获取视频ID（BV号）
    const href = e
      .querySelector(".bili-video-card__info--tit a")
      .getAttribute("href");
    data_s.video_id = href.match(/video\/(BV\w+)/)?.[1] || ""; // 正则提取BV号

    // 提取UP主信息
    data_s.up_name = e
      .querySelector(".bili-video-card__info--author")
      .textContent.trim();
    data_s.up_url = e
      .querySelector(".bili-video-card__info--owner")
      .getAttribute("href");

    // 提取发布日期（去除开头的·符号）
    const info_dates = e.querySelector(".bili-video-card__info--date");
    if (info_dates) {
      data_s.publish_date = info_dates.textContent.trim();
    } else {
      console.log(e);
      console.log("发布日期有误------------------------");
      return;
    }

    // 提取统计数据
    const card__stats = e.querySelector(".bili-video-card__stats");
    const statItems = card__stats.querySelectorAll(
      ".bili-video-card__stats--item"
    );

    // 播放量通常是第一个统计项（索引0）
    data_s.play_count =
      statItems[0]
        ?.querySelector(".bili-video-card__stats--text")
        .textContent.trim() || "0";

    // 弹幕数通常是第二个统计项（索引1）
    data_s.danmaku_count =
      statItems[1]
        ?.querySelector(".bili-video-card__stats--text")
        .textContent.trim() || "0";

    // 提取视频时长
    const durationElement = e.querySelector(
      ".bili-video-card__stats__duration"
    );

    if (durationElement) {
      data_s.duration = durationElement.textContent.trim();
    } else {
      console.log(e);
      console.log("视频时长有误------------------------");
      return;
    }

    // 提取封面图（注意选择器修正）
    const imgElement = e.querySelector(".bili-video-card__cover img");
    data_s.cover_url =
      imgElement?.getAttribute("src") ||
      imgElement?.getAttribute("data-src") ||
      "";

    // 提取点赞数（从info--icon-text中）
    const likeText =
      e
        .querySelector(".bili-video-card__info--icon-text")
        ?.textContent.trim() || "";
    data_s.like_count = likeText.replace("点赞", "").trim(); // 去除"点赞"文字

    // 将提取的数据存入临时数组
    currentBatch.push(data_s);
  });
  return currentBatch;
}
// ! 函数 结束--------------------------------------------------------------------------------------------------

const renderedVideoIds = new Set(); // 全局存储已渲染的ID
// 模板函数
function renderVideoCards(last8Videos, targetDiv) {
  // 清空目标容器
  // targetDiv.innerHTML = "";
  // 翻转数据

  last8Videos.forEach((video) => {
    if (renderedVideoIds.has(video.video_id)) {
      console.log("已渲染过，跳过");
      return; // 已渲染过，跳过
    }

    // 创建视频卡片元素
    const videoCard = document.createElement("div");
    videoCard.className = "bili-video-card is-rcmd enable-no-interest huisu";
    videoCard.setAttribute("data-report", "tianma.4-1-11.click");
    videoCard.style.setProperty("--cover-radio", "56.25%");
    videoCard.style.cssText = `
    margin: 24px 0px 0px 0px;
  `;

    // 填充视频数据到模板
    videoCard.innerHTML = `
      <div class="bili-video-card__wrap">
        <div class="bili-video-card__no-interest" style="display: none;">
          <div class="bili-video-card__no-interest--inner">
            <div class="bili-video-card__no-interest--left">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36" class="no-interest-icon" fill="currentColor">
                <path d="M3 18C3 9.715724999999999 9.715724999999999 3 18 3C26.284274999999997 3 33 9.715724999999999 33 18C33 26.284274999999997 26.284274999999997 33 18 33C9.715724999999999 33 3 26.284274999999997 3 18zM12.796710000000001 12.694004999999999C12.358049999999999 12.253995 11.645745 12.2529 11.205735 12.691575C10.765709999999999 13.130234999999999 10.764615 13.842555 11.20329 14.282565000000002L13.41144 16.494975L11.20329 18.7074C10.764615 19.147350000000003 10.765709999999999 19.8597 11.205735 20.298375C11.645745 20.73705 12.358049999999999 20.735925 12.796710000000001 20.295975L15.2682 17.81895C15.99795 17.087175000000002 15.99795 15.902775000000002 15.2682 15.17097L12.796710000000001 12.694004999999999zM24.794325 12.691575C24.354300000000002 12.2529 23.64195 12.253995 23.203274999999998 12.694004999999999L20.7318 15.17097C20.00205 15.902775000000002 20.00205 17.087175000000002 20.7318 17.81895L23.203274999999998 20.295975C23.64195 20.735925 24.354300000000002 20.73705 24.794325 20.298375C25.234274999999997 19.8597 25.2354 19.147350000000003 24.796725000000002 18.7074L22.588575 16.494975L24.796725000000002 14.282565000000002C25.2354 13.842555 25.234274999999997 13.130234999999999 24.794325 12.691575zM15.900974999999999 24.68535C16.843875 23.425575000000002 17.722649999999998 23.257199999999997 18 23.257199999999997C18.277350000000002 23.257199999999997 19.15605 23.425575000000002 20.099025 24.68535C20.471024999999997 25.182975 21.176025 25.284675 21.67365 24.912675C22.171274999999998 24.540599999999998 22.273049999999998 23.8356 21.900975 23.33805C20.5938 21.591 19.082024999999998 21.007199999999997 18 21.007199999999997C16.917900000000003 21.007199999999997 15.406125 21.591 14.09898 23.33805C13.72692 23.8356 13.82871 24.540599999999998 14.326305 24.912675C14.823929999999999 25.284675 15.5289 25.182975 15.900974999999999 24.68535z"></path>
              </svg>
              <span class="no-interest-title">不感兴趣</span>
              <span class="no-interest-desc">将减少此类内容推荐</span>
            </div>
            <div class="bili-video-card__no-interest--right">
              <div class="revert-btn">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" class="revert-icon" fill="currentColor">
                  <path d="M8.28032 2.46967C8.57321 2.76257 8.57321 3.23744 8.28032 3.53033L4.81065 7L8.28032 10.46965C8.57321 10.76255 8.57321 11.23745 8.28032 11.53035C7.98743 11.8232 7.51254 11.8232 7.21966 11.53035L3.57321 7.88389C3.08505 7.39573 3.08505 6.60428 3.57321 6.11612L7.21966 2.46967C7.51254 2.17678 7.98743 2.17678 8.28032 2.46967z"></path>
                  <path d="M3.75 7C3.75 6.58579 4.08579 6.25 4.5 6.25L14.25 6.25C17.97795 6.25 21 9.27208 21 13C21 16.72795 17.97795 19.75 14.25 19.75L7.5 19.75C7.08579 19.75 6.75 19.4142 6.75 19C6.75 18.5858 7.08579 18.25 7.5 18.25L14.25 18.25C17.1495 18.25 19.5 15.8995 19.5 13C19.5 10.10052 17.1495 7.75 14.25 7.75L4.5 7.75C4.08579 7.75 3.75 7.41421 3.75 7z"></path>
                </svg> 撤销
              </div>
            </div>
          </div>
        </div>
        <a class="bili-video-card__image--link" href="https://www.bilibili.com/video/${
          video.video_id
        }" target="_blank" data-spmid="333.1007" data-mod="tianma.4-1-11" data-idx="click">
          <div class="bili-video-card__image bili-video-card__image--hover">
            <div class="bili-video-card__image--wrap">
              <div class="bili-watch-later--wrap">
                <div class="bili-watch-later bili-watch-later--pip" style="display: none;">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20" fill="currentColor" class="bili-watch-later__icon">
                    <path d="M13.62335 5.49835C13.62335 6.3949 12.8966 7.12171 12 7.12171C11.10345 7.12171 10.37665 6.3949 10.37665 5.49835C10.37665 4.6018 11.10345 3.875 12 3.875C12.8966 3.875 13.62335 4.6018 13.62335 5.49835zM13.62345 18.4985C13.62345 19.3951 12.8966 20.12195 12 20.12195C11.10335 20.12195 10.3765 19.3951 10.3765 18.4985C10.3765 17.60185 11.10335 16.875 12 16.875C12.8966 16.875 13.62345 17.60185 13.62345 18.4985zM12 13.62485C12.89745 13.62485 13.62495 12.89735 13.62495 11.99995C13.62495 11.1025 12.89745 10.375 12 10.375C11.10255 10.375 10.37505 11.1025 10.37505 11.99995C10.37505 12.89735 11.10255 13.62485 12 13.62485z"></path>
                  </svg>
                  <span class="bili-watch-later__tip--lab" style="display: none;">添加至稍后再看</span>
                </div>
              </div>
              <picture class="v-img bili-video-card__cover">
                <source srcset="${
                  video.cover_url
                }@672w_378h_1c_!web-home-common-cover.avif" type="image/avif">
                <source srcset="${
                  video.cover_url
                }@672w_378h_1c_!web-home-common-cover.webp" type="image/webp">
                <img src="${
                  video.cover_url
                }@672w_378h_1c_!web-home-common-cover" alt="${
      video.title
    }" loading="eager">
              </picture>
              <div class="v-inline-player"></div>
            </div>
            <div class="bili-video-card__mask">
              <div class="bili-video-card__stats">
                <div class="bili-video-card__stats--left">
                  <span class="bili-video-card__stats--item">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="#ffffff" class="bili-video-card__stats--icon">
                      <path d="M12 4.99805C9.48178 4.99805 7.283 5.12616 5.73089 5.25202C4.65221 5.33949 3.81611 6.16352 3.72 7.23254C3.60607 8.4998 3.5 10.171 3.5 11.998C3.5 13.8251 3.60607 15.4963 3.72 16.76355C3.81611 17.83255 4.65221 18.6566 5.73089 18.7441C7.283 18.8699 9.48178 18.998 12 18.998C14.5185 18.998 16.7174 18.8699 18.2696 18.74405C19.3481 18.65655 20.184 17.8328 20.2801 16.76405C20.394 15.4973 20.5 13.82645 20.5 11.998C20.5 10.16965 20.394 8.49877 20.2801 7.23205C20.184 6.1633 19.3481 5.33952 18.2696 5.25205C16.7174 5.12618 14.5185 4.99805 12 4.99805zM5.60965 3.75693C7.19232 3.62859 9.43258 3.49805 12 3.49805C14.5677 3.49805 16.8081 3.62861 18.3908 3.75696C20.1881 3.90272 21.6118 5.29278 21.7741 7.09773C21.8909 8.3969 22 10.11405 22 11.998C22 13.88205 21.8909 15.5992 21.7741 16.8984C21.6118 18.7033 20.1881 20.09335 18.3908 20.23915C16.8081 20.3675 14.5677 20.498 12 20.498C9.43258 20.498 7.19232 20.3675 5.60965 20.2392C3.81206 20.0934 2.38831 18.70295 2.22603 16.8979C2.10918 15.5982 2 13.8808 2 11.998C2 10.1153 2.10918 8.39787 2.22603 7.09823C2.38831 5.29312 3.81206 3.90269 5.60965 3.75693z"></path>
                      <path d="M14.7138 10.96875C15.50765 11.4271 15.50765 12.573 14.71375 13.0313L11.5362 14.8659C10.74235 15.3242 9.75 14.7513 9.75001 13.8346L9.75001 10.1655C9.75001 9.24881 10.74235 8.67587 11.5362 9.13422L14.7138 10.96875z"></path>
                    </svg>
                    <span class="bili-video-card__stats--text">${formatNumber(
                      video.play_count
                    )}</span>
                  </span>
                  <span class="bili-video-card__stats--item">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="#ffffff" class="bili-video-card__stats--icon">
                      <path d="M12 4.99805C9.48178 4.99805 7.283 5.12616 5.73089 5.25202C4.65221 5.33949 3.81611 6.16352 3.72 7.23254C3.60607 8.4998 3.5 10.171 3.5 11.998C3.5 13.8251 3.60607 15.4963 3.72 16.76355C3.81611 17.83255 4.65221 18.6566 5.73089 18.7441C7.283 18.8699 9.48178 18.998 12 18.998C14.5185 18.998 16.7174 18.8699 18.2696 18.74405C19.3481 18.65655 20.184 17.8328 20.2801 16.76405C20.394 15.4973 20.5 13.82645 20.5 11.998C20.5 10.16965 20.394 8.49877 20.2801 7.23205C20.184 6.1633 19.3481 5.33952 18.2696 5.25205C16.7174 5.12618 14.5185 4.99805 12 4.99805zM5.60965 3.75693C7.19232 3.62859 9.43258 3.49805 12 3.49805C14.5677 3.49805 16.8081 3.62861 18.3908 3.75696C20.1881 3.90272 21.6118 5.29278 21.7741 7.09773C21.8909 8.3969 22 10.11405 22 11.998C22 13.88205 21.8909 15.5992 21.7741 16.8984C21.6118 18.7033 20.1881 20.09335 18.3908 20.23915C16.8081 20.3675 14.5677 20.498 12 20.498C9.43258 20.498 7.19232 20.3675 5.60965 20.2392C3.81206 20.0934 2.38831 18.70295 2.22603 16.8979C2.10918 15.5982 2 13.8808 2 11.998C2 10.1153 2.10918 8.39787 2.22603 7.09823C2.38831 5.29312 3.81206 3.90269 5.60965 3.75693z"></path>
                      <path d="M15.875 10.75L9.875 10.75C9.46079 10.75 9.125 10.4142 9.125 10C9.125 9.58579 9.46079 9.25 9.875 9.25L15.875 9.25C16.2892 9.25 16.625 9.58579 16.625 10C16.625 10.4142 16.2892 10.75 15.875 10.75z"></path>
                      <path d="M17.375 14.75L11.375 14.75C10.9608 14.75 10.625 14.4142 10.625 14C10.625 13.5858 10.9608 13.25 11.375 13.25L17.375 13.25C17.7892 13.25 18.125 13.5858 18.125 14C18.125 14.4142 17.7892 14.75 17.375 14.75z"></path>
                      <path d="M7.875 10C7.875 10.4142 7.53921 10.75 7.125 10.75L6.625 10.75C6.21079 10.75 5.875 10.4142 5.875 10C5.875 9.58579 6.21079 9.25 6.625 9.25L7.125 9.25C7.53921 9.25 7.875 9.58579 7.875 10z"></path>
                      <path d="M9.375 14C9.375 14.4142 9.03921 14.75 8.625 14.75L8.125 14.75C7.71079 14.75 7.375 14.4142 7.375 14C7.375 13.5858 7.71079 13.25 8.125 13.25L8.625 13.25C9.03921 13.25 9.375 13.5858 9.375 14z"></path>
                    </svg>
                    <span class="bili-video-card__stats--text">${formatNumber(
                      video.danmaku_count
                    )}</span>
                  </span>
                </div>
                <span class="bili-video-card__stats__duration">${
                  video.duration
                }</span>
              </div>
            </div>
          </div>
        </a>
        <div class="bili-video-card__info">
          <div class="bili-video-card__info--right">
            <div class="bili-video-card__info--no-interest" style="display: none;">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" class="bili-video-card__info--no-interest--icon" fill="currentColor">
                <path d="M13.62335 5.49835C13.62335 6.3949 12.8966 7.12171 12 7.12171C11.10345 7.12171 10.37665 6.3949 10.37665 5.49835C10.37665 4.6018 11.10345 3.875 12 3.875C12.8966 3.875 13.62335 4.6018 13.62335 5.49835zM13.62345 18.4985C13.62345 19.3951 12.8966 20.12195 12 20.12195C11.10335 20.12195 10.3765 19.3951 10.3765 18.4985C10.3765 17.60185 11.10335 16.875 12 16.875C12.8966 16.875 13.62345 17.60185 13.62345 18.4985zM12 13.62485C12.89745 13.62485 13.62495 12.89735 13.62495 11.99995C13.62495 11.1025 12.89745 10.375 12 10.375C11.10255 10.375 10.37505 11.1025 10.37505 11.99995C10.37505 12.89735 11.10255 13.62485 12 13.62485z"></path>
              </svg>
            </div>
            <h3 class="bili-video-card__info--tit" title="${video.title}">
              <a href="https://www.bilibili.com/video/${
                video.video_id
              }" target="_blank" data-spmid="333.1007" data-mod="tianma.4-1-11" data-idx="click">${
      video.title
    }</a>
            </h3>
            <div class="bili-video-card__info--bottom">
              <a class="bili-video-card__info--owner" href="${
                video.up_url
              }" target="_blank" data-spmid="333.1007" data-mod="tianma.4-1-11" data-idx="click">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" class="bili-video-card__info--owner__up">
                  <path d="M6.15 8.24805C6.5642 8.24805 6.9 8.58383 6.9 8.99805L6.9 12.7741C6.9 13.5881 7.55988 14.248 8.3739 14.248C9.18791 14.248 9.8478 13.5881 9.8478 12.7741L9.8478 8.99805C9.8478 8.58383 10.1836 8.24805 10.5978 8.24805C11.012 8.24805 11.3478 8.58383 11.3478 8.99805L11.3478 12.7741C11.3478 14.41655 10.01635 15.748 8.3739 15.748C6.73146 15.748 5.4 14.41655 5.4 12.7741L5.4 8.99805C5.4 8.58383 5.73578 8.24805 6.15 8.24805z"></path>
                  <path d="M12.6522 8.99805C12.6522 8.58383 12.98795 8.24805 13.4022 8.24805L15.725 8.24805C17.31285 8.24805 18.6 9.53522 18.6 11.123C18.6 12.71085 17.31285 13.998 15.725 13.998L14.1522 13.998L14.1522 14.998C14.1522 15.4122 13.8164 15.748 13.4022 15.748C12.98795 15.748 12.6522 15.4122 12.6522 14.998L12.6522 8.99805zM14.1522 12.498L15.725 12.498C16.4844 12.498 17.1 11.8824 17.1 11.123C17.1 10.36365 16.4844 9.74804 15.725 9.74804L14.1522 9.74804L14.1522 12.498z"></path>
                  <path d="M12 4.99805C9.48178 4.99805 7.283 5.12616 5.73089 5.25202C4.65221 5.33949 3.81611 6.16352 3.72 7.23254C3.60607 8.4998 3.5 10.171 3.5 11.998C3.5 13.8251 3.60607 15.4963 3.72 16.76355C3.81611 17.83255 4.65221 18.6566 5.73089 18.7441C7.283 18.8699 9.48178 18.998 12 18.998C14.5185 18.998 16.7174 18.8699 18.2696 18.74405C19.3481 18.65655 20.184 17.8328 20.2801 16.76405C20.394 15.4973 20.5 13.82645 20.5 11.998C20.5 10.16965 20.394 8.49877 20.2801 7.23205C20.184 6.1633 19.3481 5.33952 18.2696 5.25205C16.7174 5.12618 14.5185 4.99805 12 4.99805zM5.60965 3.75693C7.19232 3.62859 9.43258 3.49805 12 3.49805C14.5677 3.49805 16.8081 3.62861 18.3908 3.75696C20.1881 3.90272 21.6118 5.29278 21.7741 7.09773C21.8909 8.3969 22 10.11405 22 11.998C22 13.88205 21.8909 15.5992 21.7741 16.8984C21.6118 18.7033 20.1881 20.09335 18.3908 20.23915C16.8081 20.3675 14.5677 20.498 12 20.498C9.43258 20.498 7.19232 20.3675 5.60965 20.2392C3.81206 20.0934 2.38831 18.70295 2.22603 16.8979C2.10918 15.5982 2 13.8808 2 11.998C2 10.1153 2.10918 8.39787 2.22603 7.09823C2.38831 5.29312 3.81206 3.90269 5.60965 3.75693z"></path>
                </svg>
                <span class="bili-video-card__info--author" title="${
                  video.up_name
                }">${video.up_name}</span>
                <span class="bili-video-card__info--date">· ${
                  video.publish_date
                }</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    `;

    // 将视频卡片添加到目标容器的第一个元素之前
    if (targetDiv.firstChild) {
      targetDiv.insertBefore(videoCard, targetDiv.firstChild);
    } else {
      targetDiv.appendChild(videoCard);
    }

    renderedVideoIds.add(video.video_id); // 标记为已渲染
  });
}

// 通过属性选择器删除
function removeAllHuizuCards() {
  const cards = targetDiv.querySelectorAll(".huisu");
  if (cards.length > 0) {
    cards.forEach((card) => {
      card.remove();
      const href = card
        .querySelector(".bili-video-card__info--tit a")
        .getAttribute("href");
      video_id = href.match(/video\/(BV\w+)/)?.[1] || ""; // 正则提取BV号
      if (video_id) renderedVideoIds.delete(video_id);
    });
    return true;
  }
  return false;
}

// 辅助函数：格式化数字（如10000显示为1万）
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + "万";
  }
  return num.toString();
}

// ! 视频回溯功能 存储数据(localStorage) 开始-----------------------------------------------------------------------------------------------------------------
// 定义 localStorage 的键名
const STORAGE_KEY = "bilibili_video_data";
const SUBLIST_COUNT = 30; // 固定30个子列表
// const MAX_ITEMS_PER_LIST = 32; // 每个子列表最多32条数据

/**
 * 获取双层列表（如果不存在则返回30个空列表）
 * @return {Array}
 */
function getStoredVideoData() {
  const storedData = localStorage.getItem(STORAGE_KEY);
  return storedData ? JSON.parse(storedData) : [];
}

/**
 * 存储数据到指定子列表（双层列表结构，固定30个子列表）
 * @param {number} index - 子列表索引（0~29）
 * @param {Array} newData - 要添加的新数据
 * @return {Array} 更新后的完整双层列表
 */
function storeVideoData(index, newData, flag) {
  // 1. 获取当前存储的数据
  let videoDataLists = getStoredVideoData();
  if (videoDataLists.length === 0) {
    videoDataLists = Array.from({ length: SUBLIST_COUNT }, () => []);
  }

  // 2. 校验索引范围（必须是0~29）
  if (index < 0 || index >= SUBLIST_COUNT) {
    throw new Error(`索引超出范围！必须是 0~${SUBLIST_COUNT - 1}`);
  }

  // 3. 更新指定的子列表
  // 3. 处理新数据：若传入空数组则清空，否则合并
  const currentList = videoDataLists[index] || [];
  if (Array.isArray(newData)) {
    videoDataLists[index] =
      newData.length === 0 && flag == 0
        ? [] // 清空子列表
        : [...currentList, ...newData]; // 合并数据
  }

  // // 3. 更新指定的子列表
  // let videoDataList = videoDataLists[index];
  // videoDataList = [...videoDataList, ...newData]; // 合并新数据

  // 5. 保存回双层列表并存储

  // videoDataLists[index] = videoDataList;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(videoDataLists));

  return videoDataLists;
}

// 获取当前索引（0~29）
function getCurrentIndex() {
  const storedIndex = localStorage.getItem("currentVideoListIndex");
  return storedIndex !== null ? parseInt(storedIndex) : -1;
}

// 更新索引（自动循环 0~29）
function setCurrentIndex(index) {
  const newIndex = index % SUBLIST_COUNT; // 确保不超过 29
  localStorage.setItem("currentVideoListIndex", newIndex.toString());
}

window.addEventListener("beforeunload", function (e) {
  // 可以在这里执行一些清理操作或保存状态
  let index = getCurrentIndex();
  setCurrentIndex(index + 1);
});

window.addEventListener("load", () => {
  console.log("用户进入网站（页面完全加载）");
  let index = getCurrentIndex();
  storeVideoData(index + 1, [], 0);
  setCurrentIndex(index + 1);
});
// !视频回溯功能 结束--------------------------------------------------------------------------------------------------------------

// 隐藏部分与视频无关的盒子  B站首页第一个大卡片
var recommended = targetDiv.querySelector(".recommended-swipe");
if (recommended) {
  recommended.style.display = "none";
}

// 查找新增节点中符合条件的元素
function findNewElements(nodes, selector) {
  const newElements = [];
  nodes.forEach((node) => {
    if (node.nodeType === Node.ELEMENT_NODE) {
      //  Node.ELEMENT_NODE 它代表着一个元素节点的节点类型
      // 检查当前节点是否匹配
      if (node.matches(selector)) {
        newElements.push(node);
      }
      // 检查所有子节点（包括深层嵌套）
      if (node.querySelector(selector)) {
        newElements.push(node);
      }
    }
  });
  return newElements;
}

// 隐藏元素
function hideElements(elementsToHide) {
  requestAnimationFrame(() => {
    elementsToHide.forEach((element) => {
      // 检查当前元素或其父元素是否是 `container is-version8` 的直接子元素
      const parent = element.parentElement;
      const isDirectChild =
        parent?.classList?.contains("container") &&
        parent?.classList?.contains("is-version8");

      if (isDirectChild) {
        // 隐藏当前元素（如果是直接子元素）
        if (element.style.display !== "none") {
          element.style.display = "none";
        }
      }
      // 如果当前元素不是直接子元素，检查其父元素是否符合条件
      else if (
        parent?.parentElement?.classList?.contains("container") &&
        parent?.parentElement?.classList?.contains("is-version8")
      ) {
        // 隐藏父元素（如果父元素是 `container is-version8` 的直接子元素）
        if (parent.style.display !== "none") {
          parent.style.display = "none";
        }
      }
    });
  });
}

//! 监听 class=container 元素的子元素的变化  开始---------------------------------------------------------------------
function updateCachedElements(mutationsList) {
  var addedNodes = []; // 新增元素
  let filteredNodes = []; //保存 非回溯的节点和非元素节点

  // todo 遍历所有 DOM 变化，筛选出子节点变化的类型，然后将所有被添加的节点收集到 addedNodes 数组中。
  mutationsList.forEach((mutation) => {
    if (mutation.type === "childList") {
      addedNodes = addedNodes.concat(Array.from(mutation.addedNodes));
    }
  });

  // todo  过滤掉非回溯的节点和非元素节点 （此时保存的数据有推广，广告，直播等数据）
  filteredNodes = addedNodes.filter((node) => {
    if (node.nodeType !== Node.ELEMENT_NODE) return false;

    //  检查是否是回溯数据（通过 class 或 data-report）
    const isHuisuCard =
      node.classList?.contains("huisu") || node.querySelector(".huisu");

    return !isHuisuCard;
  });

  //todo  把数据交给分类处理函数
  return filteredNodes;
}
//! 监听 class=container 元素的子元素的变化  结束---------------------------------------------------------------------

//! 过滤掉推广，广告，直播等数据   留控制参数  开始 ------------------------------------------------------------------
var tests = [
  //过滤词集合
  // '什么',
  // '你的'
];
var regexes = tests.map((mo) => new RegExp(mo)); // 提前创建正则表达式数组(过滤词集合)
const selectorsToHide = [
  ".floor-single-card",
  // ".feed-card",
  '[class="bili-video-card is-rcmd"]',
  ".bili-live-card",
]; // 隐藏列表

function classificationProcessing(filteredNode) {
  let newElements_selector = []; //更次刷新需要隐藏的元素

  // todo 白名单  即不会过滤已关注up主的推广，广告，直播
  filteredNode = filteredNode.filter((node) => {
    const isFollowed =
      // 方式1：检查关注按钮的title
      node
        .querySelector(".bili-video-card__info--icon-text")
        ?.getAttribute("title") === "已关注" ||
      // 方式2：检查关注按钮的文本
      node
        .querySelector(".bili-video-card__info--icon-text")
        ?.textContent.includes("已关注") ||
      // 方式3：检查UP主名字旁边的关注状态
      node
        .querySelector(".bili-video-card__info--author")
        ?.nextElementSibling?.textContent.includes("已关注");

    return !isFollowed;
  });

  // todo 1.遍历过滤后的节点(标题包含过滤词过滤隐藏)
  filteredNode.forEach((node) => {
    if (node.nodeType === Node.ELEMENT_NODE) {
      const titleElement = node.querySelector(".bili-video-card__info--tit"); // 获取标题盒子
      if (titleElement) {
        const title = titleElement.getAttribute("title");
        // 检查标题是否包含过滤词
        let shouldHide = false;
        regexes.forEach((reg) => {
          if (reg.test(title)) {
            shouldHide = true;
          }
        });
        if (shouldHide) {
          console.log(`标题 "${title}" 中包含过滤词`); // 标题包含过滤词过滤隐藏
          if (node.style.display !== "none") {
            node.style.display = "none";
          }
        } else {
          // console.log(`标题 "${title}" 中不包含过滤词`);
        }
      }
    }
  });

  // todo 查找新增的需要隐藏的元素
  selectorsToHide.forEach((selector) => {
    let newElements = findNewElements(filteredNode, selector);
    newElements_selector = newElements_selector.concat(newElements);
  });

  //todo 纯净数据(无推广，广告，直播)
  let Cached_data = filteredNode.filter(
    (el) => !newElements_selector.includes(el)
  );

  // todo 提取数据并保存
  let currentBatch = extractInformation(Cached_data);

  // // 使用持久化的索引
  let lastIndex = getCurrentIndex();
  if (page_index === -10) {
    page_index = lastIndex;
  }
  if (page_index !== -10) {
    console.log("当前加载page_index", page_index);
    const updatedList = storeVideoData(page_index, currentBatch, 1);
    console.log("当前存储的数据量:", updatedList.length);
    // 更新索引
    setCurrentIndex(lastIndex);
  } else {
    console.log("没有找到非空子列表");
  }

  console.log("存储的所有数据量", getStoredVideoData());
  return newElements_selector;
}

//! 过滤掉推广，广告，直播等数据   留控制参数  结束 ------------------------------------------------------------------

const elements = targetDiv.querySelectorAll(".feed-card");
const floor_cards = targetDiv.querySelectorAll(".floor-single-card");
if (floor_cards) {
  floor_cards.forEach((floor_card) => {
    if (floor_card.style.display !== "none") {
      floor_card.style.display = "none";
    }
  });
}

let elementsToHide = [];
elements.forEach((element) => {
  elementsToHide = elementsToHide.concat(element);
});

hideElements(elementsToHide);

// 创建 MutationObserver 实例
const observer = new MutationObserver((mutationsList, observer) => {
  let filteredNodes = updateCachedElements(mutationsList);
  let elementsToHide = classificationProcessing(filteredNodes);
  hideElements(elementsToHide);
}); // 隐藏元素

// 配置观察选项
const config = { childList: true };

// 开始观察目标盒子
observer.observe(targetDiv, config);
